<template>
  <div class="container">
    <nav-bar title="确认订单" />
    <div class="address" @click="goToEditAddress">
      <div class="area">
        {{addressDefault.Address}}
        <em>{{addressDefault.Address ? '修改' : '选择收货地址'}}</em>
      </div>
      <div class="place">
        {{addressDefault.AddressDetail}}
      </div>
      <div class="customer">
        <span>{{addressDefault.ShipTo}}</span>
        <span>{{addressDefault.Phone}}</span>
      </div>
    </div>
    <div class="products">
      <div class="item" v-for="(item, index) in productList" :key="index">
        <img :src='item.imgUrl' />
        <div class="dis">
          <h3>{{item.ProductName}}</h3>
          <div class="picked">
            <span>{{item.checked}}</span>
          </div>
          <div class="price-num">
            <div class="price">
              <i>¥</i>
              <span>{{item.ProductPrice}}</span>
            </div>
            <div class="num">&times;{{item.counts}}</div>
          </div>
          <!-- <div class="labels">
            <span>支持3期免息</span>
            <span>支持7天无忧退货</span>
          </div> -->
        </div>
      </div>
      <div class="message" v-if="!isPinData">
        <span>买家留言:</span>
        <input 
          :value="orderRemarks" 
          type="text" 
          placeholder="给商家留言，最多100个字"
          @input="inputRemarks"
          @focus="getFocus"
          @blur="getBlur"
        >
      </div>
    </div>
    <div class="confirm-items">
      <div v-if="!isPinData" class="item cutoff" @click="showCouponList">
        <div class="label">优惠券</div>
        <div class="value" v-if="userCoupon.length === 0">
          无可用优惠券
        </div>
        <div class="value" v-else>
          -¥{{couponValue}}
          <i class="arrow"></i>
        </div>
      </div>
      <div class="item score" v-if="!isPinData">
        <div class="label">抵扣积分 <span>{{ canUseIntegral }} 可用</span></div>
        <div class="value">
          <div class="num-area">
            <div class="reduce" @click="reduce"></div>
            <!-- <div class="num">{{integral}}</div> -->
            <div class="num" @click="numberShow = true">{{integral}}</div>
            <van-number-keyboard
              v-model="integral"
              :show="numberShow"
              :maxlength="6"
              @blur="numberBlur"
              @input="numberIpt"
              @show="numberOnShow"
            />
            <div class="plus" @click="plus"></div>
          </div>
        </div>
      </div>
      <!-- <div class="item ticket">
        <div class="label">发票</div>
        <div class="value">
          暂不需要
          <i class="arrow"></i>
        </div>
      </div> -->
    </div>
    <div class="total-info">
      <div class="item">
        <div class="label">商品金额</div>
        <div class="value">¥{{totalPrice}}</div>
      </div>
      <div class="item" v-if="!isPinData">
        <div class="label">商品优惠券</div>
        <div class="value">-¥{{couponValue}}</div>
      </div>
      <div class="item" v-if="!isPinData">
        <div class="label">抵扣积分</div>
        <div class="value">-¥{{integral}}</div>
      </div>
    </div>
    <div class="submit-area">
      <div class="submit-con">
        <div class="total-price">实付款: ¥{{payPrice}}</div>
        <div class="submit" @click="submitOrder">提交订单</div>
      </div>
    </div>
    <van-popup 
      v-model="couponShow"
      position="bottom" 
      closeable
    >
      <div class="coupon-tit">我的优惠券</div>
      <div class="coupon-list">
        <div class="no-coupon" v-if="userCoupon.length === 0">暂无优惠券</div>
        <div class="item" :class="{'item-checked': item.checked}" v-for="(item, index) in userCoupon" :key="index">
          <div class="left">
            <h3>¥<em>{{item.Price}}</em> 优惠券</h3>
            <div class="dis">
              <p v-if="item.OrderAmount">订单满{{item.OrderAmount}}使用</p>
              <p v-else>订单金额不限制</p>
              <p>使用期限:{{item.StartTime}}-{{item.EndTime}}</p>
            </div>
          </div>
          <div class="right" v-if="item.checked" @click="useCouponSelf(index)">
            <div class="btn-get">
              <!-- <img class="iconchecked" src='../../assets/img/iconchecked.png' /> -->
              取消使用
            </div>
          </div>
          <div class="right" v-else @click="useCouponSelf(index)">
            <div class="btn-get">立即使用</div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import NavBar from 'components/common/NavBar'
import { getUserAddress } from '../../network/address'
import { getUserCoupon, getShopCoupon, userGetShopCoupon } from '../../network/coupon'
import { postSubmitOrder, postSubmitOrderByCart } from '../../network/orderConfirm'
import { getUserDetail } from '../../network/user'
import { Toast } from 'vant'

export default {
  components: {
    NavBar
  },
  data() {
    return {
      numberShow: false,
      numberFirst: true,
      userKey: localStorage.getItem('userKey'),
      userInfo: {},
      integral: '0',
      couponValue: 0,
      couponIds: '',
      orderRemarks: '',
      productList: [],
      addressList: [],
      addressDefault: {
        Address: '',
        AddressDetail: '',
        Phone: '',
        ShipTo: '',
      },
      userCoupon: [],
      shopCoupon: [],
      couponShow: false,
      checkedCouponId: '',
      isFocus: false,
      isPinData: false
    }
  },
  computed: {
    totalPrice(){
      let totalPrice = 0
      this.productList.map(item => {
       totalPrice += Number(item.ProductPrice * item.counts)
      })
      return totalPrice.toFixed(2)
    },
    payPrice(){
      let payPrice = this.totalPrice
      payPrice = payPrice - (this.integral/100) - this.couponValue
      if(payPrice<0){
        payPrice = 0
      } 
      return payPrice.toFixed(2)
    },
    canUseIntegral(){
      return this.userInfo.Integral - this.integral || 0
    }
  },
  mounted() {
    this.isPinData = !!this.$route.query.groupId

    let requestData = JSON.parse(localStorage.getItem('productRequestData'))
    this.productList = JSON.parse(localStorage.getItem('productRequestList'))

    // 如果从选择地址返回
    let address = JSON.parse(localStorage.getItem('productRequestAddress'))
    if(address){
      this.addressDefault = address
      this.integral = (requestData.integral).toString()
      this.orderRemarks = requestData.orderRemarks
    } else {
      // 请求获取用户默认地址
      getUserAddress({
        userkey: this.userKey,
      }, res => {
        let addressList = res.ShippingAddress.CanDeliveAddressList
        this.addressList = addressList
        if(this.addressList.length){ // 如果用户已设定默认地址
          let addressDefault = this.addressList.filter(item => {
            return item.IsDefault
          })[0]
          this.addressDefault = addressDefault ? addressDefault : this.addressDefault
        }
      })
    }
    this.getCoupon()
    if(!this.isPinData){
      this.useCoupon()
    }
    this.getUserScore()
  },
  methods: {
    numberIpt(e){
      if(this.numberFirst){
        setTimeout(() => {
          this.integral = e.toString()
          this.numberFirst = false
        }, 0)
      }
    },
    numberOnShow(){
      this.numberFirst = true
    },
    numberBlur(){
      this.numberShow = false
      if(this.integral === ''){
        this.integral = '0'
      }

      // 一、订单价格 和 用户积分比较，取最小值
      // 二、输入积分 超出最小值，则取最小值
      // this.integral 、 this.userInfo.Integral
      let totalPriceScore = this.totalPrice * 100 - this.couponValue * 100
      let userIntegral = this.userInfo.Integral
      let minNum =  totalPriceScore < userIntegral ? totalPriceScore : userIntegral
      console.log(totalPriceScore, userIntegral, minNum)
      if( this.integral > minNum){
        this.integral = minNum.toString()
      }
      
      // if(this.integral > this.userInfo.Integral){
      //   console.log(0)
      //   if(this.integral < this.payPrice){
      //     console.log(2)
      //     this.integral = Number(this.userInfo.Integral).toString() // 取用户积分
      //   } else {
      //     console.log(3)
      //     this.integral = Number(this.payPrice * 100).toString() // 取订单价格
      //   }
      // } 
      // else {
      //   console.log(1)
      //   this.integral = Number(this.payPrice * 100).toString() // 取订单价格
      // }
    },
    /*
      提交订单
    */
    async submitOrder(){
      if(Number(this.$route.query.action) === 0){ // 购物车方式
        let requestData0 = this.getFullRequestData0()
        console.log('提交0',requestData0)
        console.log('jsonOrderShops',JSON.stringify(requestData0))
        await this.validate(requestData0)
        
        postSubmitOrderByCart(requestData0, (orderId) => {
          console.log('提交成功, 订单ID ' + orderId)
          this.$router.push({
            path: '/pay',
            query: {
              orderId,
              payAmout: this.payPrice
            }
          })
        })
      } else
      if(Number(this.$route.query.action) === 1) { // 立刻购买方式
        let requestData1 = this.getFullRequestData1()
        console.log('提交1',requestData1)
        console.log('jsonOrderShops',JSON.stringify(requestData1))
        await this.validate(requestData1)

        postSubmitOrder(requestData1, (orderId) => {
          console.log('提交成功, 订单ID ' + orderId)
          this.$router.push({
            path: '/pay',
            query: {
              orderId,
              payAmout: this.payPrice
            }
          })
        })
      }
      
    },
    /*
      校验数据
      收货地址是否未选择
    */
    validate(data){
      return new Promise(resolve => {
        if(!data.recieveAddressId){
          Toast('请选择收货地址')
          return false
        }
        resolve()
      })
    },
    goToEditAddress(){
      this.getFullRequestData1() // 缓存订单提交数据
      this.$router.push({
        path: 'address',
        query: {
          shopId: this.$route.query.shopId,
          action: 'orderConfirm'
        }
      })
    },
    // 获取完整订单提交数据，并缓存 --- 立刻购买方式
    getFullRequestData1(){
      let requestData = JSON.parse(localStorage.getItem('productRequestData'))
      requestData.recieveAddressId = this.addressDefault.Id
      requestData.couponIds = this.couponIds==='' ? '' : this.couponIds + '_0'
      requestData.orderRemarks = this.orderRemarks
      requestData.isCashOnDelivery = ' '
      requestData.invoiceType = ' '
      requestData.invoiceTitle = ' '
      requestData.invoiceContext = ' '
      requestData.invoiceCode = ' '
      // 商品详细信息
      requestData.jsonOrderShops = [
        { 
          ShopId: this.$route.query.shopId + '', 
          OrderSkus: [{ SkuId: requestData.skuIds, Count: requestData.counts }], 
          DeliveryType: "Express", 
          ShopBrandId: 0, 
          PostOrderInvoice: { 
            InvoiceType: "None", 
            InvoiceTitle: null, 
            InvoiceCode: null, 
            InvoiceContext: null, 
            RegisterAddress: null, 
            RegisterPhone: null, 
            BankName: null, 
            BankNo: null, 
            RealName: null, 
            CellPhone: null, 
            Email: null, 
            RegionID: 0, 
            Address: null 
          } 
        } 
      ]
      requestData.CapitalAmount = ' ',
      requestData.PayPwd = ' '
      requestData.VirtualProductItems = [{
        OrderId: 0, 
        OrderItemId: 0, 
        Content: null, 
        VirtualProductItemName:"", 
        VirtualProductItemType: 1
      }]
      if(!this.isPinData){
        requestData.integral = this.integral
        requestData.ProductType = 0
      }
      localStorage.setItem('productRequestData', JSON.stringify(requestData))
      return requestData
    },
    // 获取完整订单提交数据，并缓存 --- 购物车方式
    getFullRequestData0(){
      let requestData = JSON.parse(localStorage.getItem('productRequestData'))
      requestData.integral = this.integral
      requestData.recieveAddressId = this.addressDefault.Id
      requestData.couponIds = this.couponIds==='' ? '' : this.couponIds + '_0'
      requestData.orderRemarks = this.orderRemarks
      requestData.isCashOnDelivery = ' '
      requestData.invoiceType = ' '
      requestData.invoiceTitle = ' '
      requestData.invoiceContext = ' '
      requestData.invoiceCode = ' '
      // 商品详细信息
      requestData.jsonOrderShops = [
        { 
          ShopId: this.$route.query.shopId + '', 
          OrderSkus: [{ SkuId: requestData.skuIds, Count: requestData.counts }], 
          DeliveryType: "Express", 
          ShopBrandId: 0, 
          PostOrderInvoice: { 
            InvoiceType: "None", 
            InvoiceTitle: null, 
            InvoiceCode: null, 
            InvoiceContext: null, 
            RegisterAddress: null, 
            RegisterPhone: null, 
            BankName: null, 
            BankNo: null, 
            RealName: null, 
            CellPhone: null, 
            Email: null, 
            RegionID: 0, 
            Address: null 
          } 
        } 
      ]
      requestData.CapitalAmount = ' ',
      requestData.PayPwd = ' '
      localStorage.setItem('productRequestData', JSON.stringify(requestData))
      return requestData
    },
    inputRemarks(e){
      this.orderRemarks = e.target.value
    },
    showCouponList(){
      if(this.shopCoupon.length === 0){
        return false
      }
      this.couponShow = true
    },
    getUserCoupon(cb){
      let requestData = {
        userkey: this.userKey
      }
      getUserCoupon(requestData, list => {
        // 获取未使用且未过期的用户券
        list = list.filter(item => {
          let startTime = new Date(item.StartTime).getTime()
          let endTime = new Date(item.EndTime).getTime()
          let nowTime = new Date().getTime()
          let notExpired = nowTime > startTime && nowTime < endTime
          let orderAmountFit = item.OrderAmount < this.totalPrice
          return item.UseStatus === 0 && notExpired && orderAmountFit
        })
        this.userCoupon = list
        cb && cb(list)
      })
    },
    getShopCoupon(cb){
      let requestData = {
        shopId: this.$route.query.shopId
      }
      getShopCoupon(requestData, list => {
        this.shopCoupon = list
        cb && cb(list)
      })
    },
    getCoupon(){
      this.getUserCoupon(userList => {
        this.getShopCoupon(shopList => {
          // console.log(userList, shopList)
          this.shopList = shopList.map(item => {
            let result = userList.some(itemIn => {
              return item.CouponId === itemIn.CouponId
            })
            item.exist = result
            return item
          })
        })
      })
    },
    userGetCoupon(couponId){
      let requestData = {
        userkey: this.userKey,
        vshopId: this.$route.query.shopId,
        couponId,
      }
      userGetShopCoupon(requestData, res => {
        Toast('领取成功')
        this.getCoupon()
        this.useCoupon()
      })
    },
    useCoupon(){
      this.getUserCoupon(list => {
        let itemMax = 0
        let itemId = ''
        
        list.forEach(item => {
          // 判断是否满足订单额度
          if(item.OrderAmount <= this.totalPrice){
            // 取优惠券价值最大的一张
            if(item.Price > itemMax){
              itemMax = item.Price
              itemId = item.CouponId
              this.checkedCouponId = itemId

              this.userCoupon = this.userCoupon.map(itemIn => {
                if(itemIn.CouponId === this.checkedCouponId){
                  itemIn.checked = true 
                } else {
                  itemIn.checked = false
                }
                return itemIn
              })
            }
          }
        })
        this.couponValue = itemMax
        this.couponIds = itemId
      })
    },
    useCouponSelf(index){
      let userCoupon = this.userCoupon[index]
      if(!userCoupon.checked){
        this.checkedCouponId = userCoupon.CouponId
        this.couponValue = userCoupon.Price
        this.couponIds = userCoupon.CouponId
      } else {
        this.checkedCouponId = ''
        this.couponValue = 0
        this.couponIds = ''
      }
      this.$set(this.userCoupon[index], 'checked', !this.userCoupon[index].checked)

      this.userCoupon = this.userCoupon.map((item, idx) => {
        if(idx !== index){
          item.checked = false
        }
        return item
      })
      this.couponShow = false
    },
    getFocus(){
      this.isFocus = true
    },
    getBlur(){
      this.isFocus = false
      setTimeout(() => {
        if(!this.isFocus){
          this.checkVersion(window.scrollY)
        }
      }, 200)
    },
    checkVersion(y){
      let resultArr = navigator.userAgent.match(/iPhone\sOS\s(\d+)/)
      if(resultArr && resultArr.length > 1){
        let iosVersion = resultArr[1]*1
        if(iosVersion > 12){
          window.scrollTo(0,y)
        }
      }
    },
    reduce(){
      if(this.integral>0){
        this.integral = (this.integral - 1).toString()
      }
    },
    plus(){
      if(this.integral < this.userInfo.Integral
        && this.payPrice >= 0.01
      ){
        this.integral = (Number(this.integral) + 1).toString()
      }
    },
    getUserScore(){
      let requestData = {
        userKey: this.userKey
      }
      getUserDetail(requestData, info => {
        this.userInfo = info
      })
    }
  },
}
</script>

<style scoped>
.address{
  padding: 30px 30px 40px 30px;
  margin-bottom: 15px;
  background-color: #ffffff;
}
.address span{
  padding-right: 10px;
}
.address .place{
  font-size: 24px;
  line-height: 2.5;
}
.address .area{
  display: flex;
  justify-content: space-between;
}
.address .area em{
  padding-left: 20px;
  color: #999;
  font-size: 14px;
}
.products{
  padding-left: 20px;
  background-color: #ffffff;
}
.products .item{
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  padding: 15px 10px 15px 0;
  border-bottom: 1px solid #e7e7e7;
  background-color: #ffffff;
}
.products .item img{
  flex-shrink: 0;
  width: 72px;
  height: 72px;
  margin-right: 10px;
  border-radius: 3px;
}
.products .item .dis{
  flex-grow: 1;
  min-width: 100px;
  font-size: 14px;
  display: flex;
  flex-direction: column;
}
.products .item .dis h3{
  font-size: 14px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.products .item .dis .picked{
  display: flex;
  align-items: center;
  border-radius: 3px;
  color: #999999;
  display: inline-block;
  padding: 4px 0 9px 0;
}
.products .item .dis .price-num{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.products .item .dis .time{
  color: #999999;
}
.products .item .dis .price span{
  font-size: 16px;
  padding-left: 5px;
}
.products .item .labels{
  margin-top: 10px;
}
.products .item .labels span{
  padding: 3px 5px;
  border-radius: 20px;
  margin-right: 5px;
  font-size: 12px;
  color: #f56c6c;
  background-color: #fef0f0;
}
.message{
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  display: flex;
  align-items: stretch;
}
.message span{
  margin-right: 10px;
}
.message input{
  line-height: 20px;
}
.confirm-items{
  margin-top: 10px;
  padding: 0 15px;
  background-color: #fff;
}
.confirm-items .item{
  position: relative;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e7e7e7;
}
.confirm-items .item:last-child{
  border-bottom: none;
}
.confirm-items .item .value{
  display: flex;
  align-items: center;
}
.confirm-items .item .value i{
  display: inline-block;
  width: 7px;
  height: 7px;
  border-top: 1px solid #999;
  border-right: 1px solid #999;
  transform: rotate(45deg);
  margin-left: 10px;
}
.confirm-items .item.score span{
  font-size: 14px;
  color: #999;
}
.num-area{
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #e4e4e4;
  border-radius: 3px;
}
.num-area .reduce,
.num-area .plus{
  position: relative;
  width: 30px;
  height: 30px;
  text-align: center;
}
.num-area .num{
  width: 60px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-left: 1px solid #e4e4e4;
  border-right: 1px solid #e4e4e4;
}
.num-area .reduce:before,
.num-area .plus:before{
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -4px;
  content: '';
  display: block;
  width: 9px;
  height: 1px;
  background-color: #999999;
}
.num-area .plus:after{
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -5px;
  content: '';
  display: block;
  width: 1px;
  height: 10px;
  background-color: #999999;
}
.total-info{
  margin: 10px 0;
  padding: 5px 15px;
  background-color: #fff;
}
.total-info .item{
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
}
.total-info .item .value{
  color: #f56c6c;
}
.submit-area{
  height: 60px;
}
.submit-con{
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  line-height: 60px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
}
.submit-con .submit{
  width: 100px;
  color: #fff;
  text-align: center;
  background-color: #000;
}
.submit-con .total-price{
  flex-grow: 1;
  padding-left: 15px;
  border-top: 1px solid #e4e4e4;
}
.coupon-list{
  padding: 15px;
}
.coupon-tit{
  text-align: center;
  line-height: 50px;
  padding-top: 5px;
}
.coupon-list .item{
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
  color: #f86930
}
.coupon-list .item .left{
  flex-grow: 1;
  padding: 10px;
  border-radius: 8px;
  background-color: #ffe8df;
}
.coupon-list .item .left h3 em{
  font-size: 32px;
  font-weight: bold;
  padding: 0 5px;
}
.coupon-list .item .left .dis{
  font-size: 12px;
}
.coupon-list .item .right{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  border-left: 1px dashed #ffc6af;
  flex-shrink: 0;
  background-color: #ffe8df;
  border-radius: 8px;
}
.coupon-list .item .right.exist{
  background-image: url("../../assets/img/exist.png");
  background-position: right bottom;
  background-size: 50px auto;
  background-repeat: no-repeat;
}
.coupon-list .item .right .btn-get{
  color: #ffffff;
  padding: 6px 15px;
  border-radius: 80px;
  font-size: 12px;
  background-color: #f86930;
}
.no-coupon{
  line-height: 3;
  text-align: center;
  font-size: 16px;
  padding: 20px;
  color: #999;
}
.coupon-list .item-checked .left,
.coupon-list .item-checked .right{
  color: #fff;
  background-color: #f86930;
}
.iconchecked{
  width: 20px;
}
</style>